﻿namespace Fiddler
{
    using Microsoft.Win32;
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Globalization;
    using System.IO;
    using System.Net.NetworkInformation;
    using System.Reflection;
    using System.Runtime.CompilerServices;
    using System.Security.Authentication;
    using System.Text;
    using System.Windows.Forms;

    public static class CONFIG
    {
        private static ProcessFilterCategories _pfcDecyptFilter;
        [CompilerGenerated]
        private static bool _bRevertToDefaultLayout;
        [CompilerGenerated]
        private static int _iReverseProxyForPort;
        internal static bool bAlwaysShowTrayIcon;
        public static bool bAttachOnBoot;
        public static bool bAutoLoadScript;
        public static bool bAutoProxyLogon;
        public static bool bAutoScroll;
        public static bool bBreakOnImages;
        public static bool bCaptureCONNECT;
        public static bool bCaptureFTP;
        internal static bool bCheckCompressionIntegrity;
        public static bool bDebugCertificateGeneration;
        internal static bool bDebugSpew;
        public static bool bEnableIPv6;
        public static bool bForwardToGateway;
        public static bool bHideOnMinimize;
        internal static bool bHookAllConnections;
        internal static bool bHookWithPAC;
        private static bool bIgnoreServerCertErrors;
        internal static bool bIsBeta;
        internal static bool bIsViewOnly;
        public static bool bLoadExtensions;
        public static bool bLoadInspectors;
        public static bool bLoadScript;
        public static bool bMapSocketToProcess;
        public static bool bMITM_HTTPS;
        private static bool bQuietMode;
        public static bool bReportHTTPErrors;
        internal static bool bReportHTTPLintErrors;
        public static bool bResetCounterOnClear;
        public static bool bReuseClientSockets;
        public static bool bReuseServerSockets;
        internal static bool bRunningOnCLRv4;
        public static bool bSearchUnmarkOldHits;
        internal static bool bShowDefaultClientCertificateNeededPrompt;
        public static bool bSmartScroll;
        [Obsolete("Do not use this field. Watch the preference fiddler.ui.layout.mode instead.")]
        public static bool bStackedLayout;
        internal static bool bStreamAudioVideo;
        public static bool bUseAESForSAZ;
        public static bool bUseEventLogForExceptions;
        internal static bool bUseSNIForCN;
        internal static bool bUseXceedDecompressForDeflate;
        internal static bool bUseXceedDecompressForGZIP;
        internal static bool bUsingPortOverride;
        public static bool bVersionCheck;
        internal static bool bVersionCheckBlocked;
        private static readonly System.Drawing.Color COLOR_DEFAULT_DISABLEDEDIT;
        private static readonly System.Drawing.Color COLOR_HICONTRASTDARK_DISABLEDEDIT;
        public static System.Drawing.Color colorDisabledEdit;
        public static Version FiddlerVersionInfo;
        public static float flFontSize;
        internal const int I_MAX_CONNECTION_QUEUE = 50;
        public static int iHotkey;
        public static int iHotkeyMod;
        public static int iReporterUpdateInterval;
        public static int iScriptReloadInterval;
        internal static ProcessFilterCategories iShowProcessFilter;
        internal static uint iStartupCount;
        private static bool m_bAllowRemoteConnections;
        private static bool m_bCheckForISA;
        private static bool m_bForceExclusivePort;
        private static string m_CompareTool;
        private static string m_JSEditor;
        private static int m_ListenPort;
        public static string m_sAdditionalScriptReferences;
        private static string m_sHostsThatBypassFiddler;
        private static string m_TextEditor;
        public static SslProtocols oAcceptedClientHTTPSProtocols;
        public static SslProtocols oAcceptedServerHTTPSProtocols;
        public static Encoding oHeaderEncoding;
        internal static HostList oHLSkipDecryption;
        public static string sAlternateHostname;
        internal static string sFiddlerListenHostPort;
        public static string sGatewayPassword;
        public static string sGatewayUsername;
        internal static string sHookConnectionNamed;
        internal static string sMachineDomain;
        internal static string sMachineName;
        internal static string sMakeCertParamsEE;
        internal static string sMakeCertParamsRoot;
        internal static string sMakeCertRootCN;
        internal static string sMakeCertSubjectO;
        internal static string sReverseProxyHostname;
        internal static string sRootKey;
        private static string sRootUrl;
        private static string sScriptPath;
        private static string sSecureRootUrl;
        private static string sUserPath;

        static CONFIG()
        {
            RegistryKey key;
            bRunningOnCLRv4 = Environment.Version.Major > 3;
            bQuietMode = !Environment.UserInteractive;
            _pfcDecyptFilter = ProcessFilterCategories.All;
            bSearchUnmarkOldHits = true;
            bResetCounterOnClear = true;
            bSmartScroll = true;
            bAutoScroll = true;
            flFontSize = 8.25f;
            COLOR_DEFAULT_DISABLEDEDIT = System.Drawing.Color.AliceBlue;
            COLOR_HICONTRASTDARK_DISABLEDEDIT = System.Drawing.Color.FromArgb(0, 0, 50);
            colorDisabledEdit = COLOR_DEFAULT_DISABLEDEDIT;
            bIsViewOnly = false;
            bUseXceedDecompressForGZIP = false;
            bUseXceedDecompressForDeflate = true;
            bMapSocketToProcess = true;
            bMITM_HTTPS = false;
            bUseSNIForCN = false;
            bIgnoreServerCertErrors = false;
            bStreamAudioVideo = true;
            iStartupCount = 0;
            bCheckCompressionIntegrity = false;
            bShowDefaultClientCertificateNeededPrompt = true;
            sFiddlerListenHostPort = "127.0.0.1:8888";
            sMakeCertParamsRoot = "-r -ss my -n \"CN={0}{1}\" -sky signature -eku 1.3.6.1.5.5.7.3.1 -h 1 -cy authority -a sha1 -m 120 -b {3}{4}";
            sMakeCertParamsEE = "-pe -ss my -n \"CN={0}{1}\" -sky exchange -in {2} -is my -eku 1.3.6.1.5.5.7.3.1 -cy end -a sha1 -m 120 -b {3}{4}";
            sMakeCertRootCN = "DO_NOT_TRUST_FiddlerRoot";
            sMakeCertSubjectO = ", O=DO_NOT_TRUST, OU=Created by http://www.fiddler2.com";
            sRootUrl = "http://www.fiddler2.com/fiddler2/";
            sSecureRootUrl = "https://www.fiddler2.com/";
            sRootKey = @"SOFTWARE\Microsoft\Fiddler2\";
            sUserPath = string.Concat(new object[] { GetPath("MyDocs"), Path.DirectorySeparatorChar, "Fiddler2", Path.DirectorySeparatorChar });
            sScriptPath = string.Concat(new object[] { sUserPath, "Scripts", Path.DirectorySeparatorChar, "CustomRules.js" });
            bUseAESForSAZ = true;
            oAcceptedClientHTTPSProtocols = SslProtocols.Default;
            oAcceptedServerHTTPSProtocols = SslProtocols.Default;
            FiddlerVersionInfo = Assembly.GetExecutingAssembly().GetName().Version;
            bIsBeta = false;
            bForwardToGateway = true;
            bDebugSpew = false;
            oHeaderEncoding = Encoding.UTF8;
            bAttachOnBoot = true;
            bLoadInspectors = true;
            bLoadExtensions = true;
            bLoadScript = true;
            bAutoLoadScript = true;
            bReportHTTPErrors = true;
            bReportHTTPLintErrors = false;
            iReporterUpdateInterval = 500;
            iScriptReloadInterval = 0xbb8;
            bHideOnMinimize = false;
            bAlwaysShowTrayIcon = false;
            bStackedLayout = false;
            bVersionCheck = true;
            bBreakOnImages = false;
            m_TextEditor = "notepad.exe";
            m_CompareTool = "windiff.exe";
            bReuseServerSockets = true;
            bReuseClientSockets = true;
            bCaptureCONNECT = true;
            bCaptureFTP = false;
            bUseEventLogForExceptions = false;
            bAutoProxyLogon = false;
            bEnableIPv6 = Environment.OSVersion.Version.Major > 5;
            sHookConnectionNamed = "DefaultLAN";
            bHookAllConnections = true;
            bHookWithPAC = false;
            m_bCheckForISA = true;
            m_ListenPort = 0x22b8;
            bUsingPortOverride = false;
            bDebugCertificateGeneration = true;
            sAlternateHostname = "?";
            sReverseProxyHostname = "localhost";
            sMachineName = string.Empty;
            sMachineDomain = string.Empty;
            iHotkeyMod = 3;
            iHotkey = 70;
            oHLSkipDecryption = null;
            try
            {
                IPGlobalProperties iPGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
                sMachineDomain = iPGlobalProperties.DomainName.ToLowerInvariant();
                sMachineName = iPGlobalProperties.HostName.ToLowerInvariant();
                iPGlobalProperties = null;
            }
            catch (Exception)
            {
            }
            try
            {
                key = Registry.LocalMachine.OpenSubKey(GetRegPath("LMIsBeta"), RegistryKeyPermissionCheck.ReadSubTree);
                if (key != null)
                {
                    bIsBeta = Utilities.GetRegistryBool(key, "IsBeta", bIsBeta);
                    bVersionCheckBlocked = Utilities.GetRegistryBool(key, "BlockUpdateCheck", bVersionCheckBlocked);
                    if (Utilities.GetRegistryBool(key, "ForceViewerMode", false))
                    {
                        bIsViewOnly = true;
                    }
                    if (bVersionCheckBlocked)
                    {
                        bFIP = bVersionCheck = false;
                    }
                    key.Close();
                }
            }
            catch (Exception)
            {
            }
            key = Registry.CurrentUser.OpenSubKey(sRootKey, RegistryKeyPermissionCheck.ReadSubTree);
            if (key != null)
            {
                m_bForceExclusivePort = Utilities.GetRegistryBool(key, "ExclusivePort", m_bForceExclusivePort);
                bUseEventLogForExceptions = Utilities.GetRegistryBool(key, "UseEventLogForExceptions", bUseEventLogForExceptions);
                m_bCheckForISA = Utilities.GetRegistryBool(key, "CheckForISA", m_bCheckForISA);
                m_TextEditor = (string) key.GetValue("TextEditor", m_TextEditor);
                m_CompareTool = (string) key.GetValue("CompareTool", m_CompareTool);
                bBreakOnImages = Utilities.GetRegistryBool(key, "BreakOnImages", bBreakOnImages);
                sHostsThatBypassFiddler = (string) key.GetValue("FiddlerBypass", string.Empty);
                sGatewayUsername = (string) key.GetValue("GatewayUsername", sGatewayUsername);
                sGatewayPassword = (string) key.GetValue("GatewayPassword", sGatewayPassword);
                sMakeCertParamsRoot = (string) key.GetValue("MakeCertParamsRoot", sMakeCertParamsRoot);
                sMakeCertParamsEE = (string) key.GetValue("MakeCertParamsEE", sMakeCertParamsEE);
                sMakeCertRootCN = (string) key.GetValue("MakeCertRootCN", sMakeCertRootCN);
                sMakeCertSubjectO = (string) key.GetValue("MakeCertSubjectO", sMakeCertSubjectO);
                m_JSEditor = (string) key.GetValue("JSEditor", m_JSEditor);
                ListenPort = Utilities.GetRegistryInt(key, "ListenPort", m_ListenPort);
                bLoadScript = Utilities.GetRegistryBool(key, "LoadScript", bLoadScript);
                bLoadInspectors = Utilities.GetRegistryBool(key, "LoadInspectors", bLoadInspectors);
                bLoadExtensions = Utilities.GetRegistryBool(key, "LoadExtensions", bLoadExtensions);
                foreach (string str in Environment.GetCommandLineArgs())
                {
                    if (str.StartsWith("-") || str.StartsWith("/"))
                    {
                        if (str.IndexOf("port:", StringComparison.OrdinalIgnoreCase) == 1)
                        {
                            int result = 0;
                            if (int.TryParse(str.Substring(str.IndexOf("port:", StringComparison.OrdinalIgnoreCase) + 5), NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out result))
                            {
                                ListenPort = result;
                                bUsingPortOverride = true;
                            }
                        }
                        else if (str.IndexOf("quiet", StringComparison.OrdinalIgnoreCase) == 1)
                        {
                            bQuietMode = true;
                        }
                        else if (str.IndexOf("extoff", StringComparison.OrdinalIgnoreCase) == 1)
                        {
                            bLoadExtensions = bLoadInspectors = false;
                        }
                        else if (str.IndexOf("noscript", StringComparison.OrdinalIgnoreCase) == 1)
                        {
                            bLoadScript = false;
                        }
                        else if (str.IndexOf("viewer", StringComparison.OrdinalIgnoreCase) == 1)
                        {
                            bIsViewOnly = true;
                        }
                        else if (str.IndexOf("?", StringComparison.OrdinalIgnoreCase) == 1)
                        {
                            _ShowCommandLineArgs();
                        }
                    }
                }
                iHotkeyMod = Utilities.GetRegistryInt(key, "HotkeyMod", iHotkeyMod);
                iHotkey = Utilities.GetRegistryInt(key, "Hotkey", iHotkey);
                flFontSize = Utilities.GetRegistryFloat(key, "FontSize", flFontSize);
                flFontSize = Math.Min(flFontSize, 24f);
                flFontSize = Math.Max(flFontSize, 4f);
                int argb = Utilities.GetRegistryInt(key, "colorDisabledEdit", -1);
                if (argb != -1)
                {
                    colorDisabledEdit = System.Drawing.Color.FromArgb(argb);
                }
                if ((SystemInformation.HighContrast && (colorDisabledEdit == COLOR_DEFAULT_DISABLEDEDIT)) && (System.Drawing.Color.FromKnownColor(KnownColor.WindowText).GetBrightness() > 0.2))
                {
                    colorDisabledEdit = COLOR_HICONTRASTDARK_DISABLEDEDIT;
                }
                bAttachOnBoot = Utilities.GetRegistryBool(key, "AttachOnBoot", bAttachOnBoot);
                iStartupCount = (uint) (1 + Utilities.GetRegistryInt(key, "StartupCount", 0));
                bAutoLoadScript = Utilities.GetRegistryBool(key, "AutoReloadScript", bAutoLoadScript);
                m_bAllowRemoteConnections = Utilities.GetRegistryBool(key, "AllowRemote", m_bAllowRemoteConnections);
                bReuseServerSockets = Utilities.GetRegistryBool(key, "ReuseServerSockets", bReuseServerSockets);
                bReuseClientSockets = Utilities.GetRegistryBool(key, "ReuseClientSockets", bReuseClientSockets);
                bAutoProxyLogon = Utilities.GetRegistryBool(key, "AutoProxyLogon", bAutoProxyLogon);
                bDebugSpew = Utilities.GetRegistryBool(key, "DebugSpew", bDebugSpew);
                bReportHTTPErrors = Utilities.GetRegistryBool(key, "ReportHTTPErrors", bReportHTTPErrors);
                if (bDebugSpew)
                {
                    FiddlerApplication.Log.LogString("Fiddler DebugSpew is enabled.");
                    Trace.WriteLine("Fiddler DebugSpew is enabled.");
                }
                bHideOnMinimize = Utilities.GetRegistryBool(key, "HideOnMinimize", bHideOnMinimize);
                bAlwaysShowTrayIcon = Utilities.GetRegistryBool(key, "AlwaysShowTrayIcon", bAlwaysShowTrayIcon);
                bForwardToGateway = Utilities.GetRegistryBool(key, "UseGateway", bForwardToGateway);
                bEnableIPv6 = Utilities.GetRegistryBool(key, "EnableIPv6", bEnableIPv6);
                bCaptureCONNECT = Utilities.GetRegistryBool(key, "CaptureCONNECT", bCaptureCONNECT);
                bCaptureFTP = Utilities.GetRegistryBool(key, "CaptureFTP", bCaptureFTP);
                bMapSocketToProcess = Utilities.GetRegistryBool(key, "MapSocketToProcess", bMapSocketToProcess);
                bUseXceedDecompressForGZIP = Utilities.GetRegistryBool(key, "UseXceedDecompressForGZIP", bUseXceedDecompressForGZIP);
                bUseXceedDecompressForDeflate = Utilities.GetRegistryBool(key, "UseXceedDecompressForDeflate", bUseXceedDecompressForDeflate);
                bUseAESForSAZ = !Utilities.GetRegistryBool(key, "UseLegacyEncryptionForSaz", false);
                bStreamAudioVideo = Utilities.GetRegistryBool(key, "AutoStreamAudioVideo", bStreamAudioVideo);
                bShowDefaultClientCertificateNeededPrompt = Utilities.GetRegistryBool(key, "ShowDefaultClientCertificateNeededPrompt", bShowDefaultClientCertificateNeededPrompt);
                bMITM_HTTPS = Utilities.GetRegistryBool(key, "CaptureHTTPS", bMITM_HTTPS);
                bIgnoreServerCertErrors = Utilities.GetRegistryBool(key, "IgnoreServerCertErrors", bIgnoreServerCertErrors);
                iReverseProxyForPort = Utilities.GetRegistryInt(key, "ReverseProxyForPort", iReverseProxyForPort);
                sReverseProxyHostname = (string) key.GetValue("ReverseProxyHostname", sReverseProxyHostname);
                if (!bVersionCheckBlocked)
                {
                    bVersionCheck = Utilities.GetRegistryBool(key, "CheckForUpdates", bVersionCheck);
                }
                if (FiddlerApplication.Prefs != null)
                {
                    if (bReportHTTPErrors)
                    {
                        bReportHTTPLintErrors = FiddlerApplication.Prefs.GetBoolPref("fiddler.lint.HTTP", false);
                    }
                    if (!FiddlerApplication.Prefs.GetBoolPref("fiddler.filters.ResetOnRestart", false))
                    {
                        iShowProcessFilter = (ProcessFilterCategories) Utilities.GetRegistryInt(key, "ShowProcessFilter", (int) iShowProcessFilter);
                        DecryptWhichProcesses = (ProcessFilterCategories) Utilities.GetRegistryInt(key, "HTTPSProcessFilter", (int) DecryptWhichProcesses);
                    }
                    bUseSNIForCN = FiddlerApplication.Prefs.GetBoolPref("fiddler.network.https.SetCNFromSNI", false);
                    string stringPref = FiddlerApplication.Prefs.GetStringPref("fiddler.network.https.SupportedClientProtocolVersions", null);
                    if (!string.IsNullOrEmpty(stringPref))
                    {
                        oAcceptedClientHTTPSProtocols = Utilities.ParseSSLProtocolString(stringPref);
                    }
                    stringPref = FiddlerApplication.Prefs.GetStringPref("fiddler.network.https.SupportedServerProtocolVersions", null);
                    if (!string.IsNullOrEmpty(stringPref))
                    {
                        oAcceptedServerHTTPSProtocols = Utilities.ParseSSLProtocolString(stringPref);
                    }
                }
                else
                {
                    MessageBox.Show("Objects expected to exist after Fiddler startup are missing. Please report this error message using the Help > Contact link. Thanks!", "Inconceivable!");
                }
                m_sAdditionalScriptReferences = (string) key.GetValue("ScriptReferences", string.Empty);
                sHookConnectionNamed = (string) key.GetValue("HookConnectionNamed", sHookConnectionNamed);
                bHookAllConnections = Utilities.GetRegistryBool(key, "HookAllConnections", bHookAllConnections);
                bHookWithPAC = Utilities.GetRegistryBool(key, "HookWithPAC", bHookWithPAC);
                if (key.GetValue("HeaderEncoding") != null)
                {
                    try
                    {
                        oHeaderEncoding = Encoding.GetEncoding((string) key.GetValue("HeaderEncoding"));
                    }
                    catch (Exception exception)
                    {
                        FiddlerApplication.DoNotifyUser(exception.Message, "Invalid HeaderEncoding specified in registry");
                        oHeaderEncoding = Encoding.UTF8;
                    }
                }
                sUserPath = (string) key.GetValue("UserPath", sUserPath);
                if (!sUserPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                {
                    sUserPath = sUserPath + Path.DirectorySeparatorChar;
                }
                sScriptPath = (string) key.GetValue("ScriptFullPath", string.Concat(new object[] { sUserPath, "Scripts", Path.DirectorySeparatorChar, "CustomRules.js" }));
                key.Close();
            }
            if ((Environment.OSVersion.Version.Major < 6) && (Environment.OSVersion.Version.Minor < 1))
            {
                bMapSocketToProcess = false;
            }
        }

        private static void _ShowCommandLineArgs()
        {
            string sMessage = "Usage:\n\tfiddler.exe [options] [FileToLoad.saz]\n\nOptions:\n\n-viewer\t\tLoad a new Fiddler window in non-proxy 'Viewer' mode\n-quiet\t\tSuppress prompts and alerts, minimize to the tray\n-noattach\t\tDo not register as the system proxy on startup\n-noversioncheck\tDo not check for new versions on startup\n-extoff\t\tDo not load Fiddler extensions\n-noscript\t\tDo not load FiddlerScript\n-port:####\tRun proxy on specified port\n-?\t\tShow this help content\n";
            FiddlerApplication.DoNotifyUser(sMessage, "Fiddler Command-Line Help");
        }

        internal static void EnsureFoldersExist()
        {
            try
            {
                if (!Directory.Exists(GetPath("Captures")))
                {
                    Directory.CreateDirectory(GetPath("Captures"));
                }
                if (!Directory.Exists(GetPath("Requests")))
                {
                    Directory.CreateDirectory(GetPath("Requests"));
                }
                if (!Directory.Exists(GetPath("Responses")))
                {
                    Directory.CreateDirectory(GetPath("Responses"));
                }
                if (!Directory.Exists(GetPath("Scripts")))
                {
                    Directory.CreateDirectory(GetPath("Scripts"));
                }
            }
            catch (Exception exception)
            {
                FiddlerApplication.DoNotifyUser(exception.ToString(), "Folder Creation Failed");
            }
            try
            {
                if ((!FiddlerApplication.Prefs.GetBoolPref("fiddler.script.delaycreate", true) && !File.Exists(GetPath("CustomRules"))) && File.Exists(GetPath("SampleRules")))
                {
                    File.Copy(GetPath("SampleRules"), GetPath("CustomRules"));
                }
            }
            catch (Exception exception2)
            {
                FiddlerApplication.DoNotifyUser(exception2.ToString(), "Initial file copies failed");
            }
        }

        [CodeDescription("Return a filesystem path.")]
        public static string GetPath(string sWhatPath)
        {
            string folderPath;
            switch (sWhatPath)
            {
                case "App":
                    return (Path.GetDirectoryName(Application.ExecutablePath) + Path.DirectorySeparatorChar);

                case "AutoFiddlers_Machine":
                    return string.Concat(new object[] { Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar, "Scripts", Path.DirectorySeparatorChar });

                case "AutoFiddlers_User":
                    return (sUserPath + "Scripts" + Path.DirectorySeparatorChar);

                case "AutoResponderDefaultRules":
                    return (sUserPath + "AutoResponder.xml");

                case "Captures":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.captures", sUserPath + "Captures" + Path.DirectorySeparatorChar);

                case "CustomRules":
                    return sScriptPath;

                case "DefaultClientCertificate":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.defaultclientcert", sUserPath + "ClientCertificate.cer");

                case "FiddlerRootCert":
                    return (sUserPath + "DO_NOT_TRUST_FiddlerRoot.cer");

                case "Filters":
                    return (sUserPath + "Filters" + Path.DirectorySeparatorChar);

                case "Inspectors":
                    return string.Concat(new object[] { Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar, "Inspectors", Path.DirectorySeparatorChar });

                case "PerUser-ISA-Config":
                    folderPath = @"C:\";
                    try
                    {
                        folderPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
                    }
                    catch (Exception)
                    {
                    }
                    return (folderPath + @"\microsoft\firewall client 2004\management.ini");

                case "PerMachine-ISA-Config":
                    folderPath = @"C:\";
                    try
                    {
                        folderPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
                    }
                    catch (Exception)
                    {
                    }
                    return (folderPath + @"\microsoft\firewall client 2004\management.ini");

                case "MakeCert":
                    folderPath = FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.makecert", Path.GetDirectoryName(Application.ExecutablePath) + @"\MakeCert.exe");
                    if (!File.Exists(folderPath))
                    {
                        folderPath = "MakeCert.exe";
                    }
                    return folderPath;

                case "MyDocs":
                    folderPath = @"C:\";
                    try
                    {
                        folderPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                    }
                    catch (Exception exception)
                    {
                        FiddlerApplication.DoNotifyUser("Initialization Error", "Failed to retrieve path to your My Documents folder.\nThis generally means you have a relative environment variable.\nDefaulting to C:\\\n\n" + exception.Message);
                    }
                    return folderPath;

                case "Pac":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.pac", sUserPath + @"Scripts\BrowserPAC.js");

                case "Requests":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.requests", sUserPath + @"Captures\Requests\");

                case "Responses":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.responses", sUserPath + @"Captures\Responses\");

                case "Root":
                    return sUserPath;

                case "QuickExecHistory":
                    return (sUserPath + @"\QuickExecHistory.txt");

                case "SafeTemp":
                    folderPath = @"C:\";
                    try
                    {
                        folderPath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
                    }
                    catch (Exception exception2)
                    {
                        FiddlerApplication.DoNotifyUser("Failed to retrieve path to your Internet Cache folder.\nThis generally means you have a relative environment variable.\nDefaulting to C:\\\n\n" + exception2.Message, "GetPath(SafeTemp) Failed");
                    }
                    return folderPath;

                case "SampleRules":
                    return (Path.GetDirectoryName(Application.ExecutablePath) + @"\Scripts\SampleRules.js");

                case "Scripts":
                    return (sUserPath + "Scripts" + Path.DirectorySeparatorChar);

                case "TemplateResponses":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.templateresponses", string.Concat(new object[] { Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar, "ResponseTemplates", Path.DirectorySeparatorChar }));

                case "TextEditor":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.texteditor", m_TextEditor);

                case "Tools":
                    return FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.Tools", string.Concat(new object[] { Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar, "Tools", Path.DirectorySeparatorChar }));

                case "Transcoders_Machine":
                    return string.Concat(new object[] { Path.GetDirectoryName(Application.ExecutablePath), Path.DirectorySeparatorChar, "ImportExport", Path.DirectorySeparatorChar });

                case "Transcoders_User":
                    return (sUserPath + "ImportExport" + Path.DirectorySeparatorChar);

                case "WINDIFF":
                {
                    string stringPref = FiddlerApplication.Prefs.GetStringPref("fiddler.config.path.differ", null);
                    if (string.IsNullOrEmpty(stringPref))
                    {
                        if (m_CompareTool == "windiff.exe")
                        {
                            if (File.Exists(GetPath("App") + "windiff.exe"))
                            {
                                return (GetPath("App") + "windiff.exe");
                            }
                            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinMerge.exe", false);
                            if (key != null)
                            {
                                string str3 = (string) key.GetValue(string.Empty, null);
                                key.Close();
                                if (str3 != null)
                                {
                                    return str3;
                                }
                            }
                        }
                        return m_CompareTool;
                    }
                    return stringPref;
                }
            }
            return @"C:\";
        }

        public static string GetRegPath(string sWhatPath)
        {
            switch (sWhatPath)
            {
                case "Root":
                    return sRootKey;

                case "LMIsBeta":
                    return sRootKey;

                case "MenuExt":
                    return (sRootKey + @"MenuExt\");

                case "UI":
                    return (sRootKey + @"UI\");

                case "MRU":
                    return sRootKey;

                case "Dynamic":
                    return (sRootKey + @"Dynamic\");

                case "Prefs":
                    return (sRootKey + @"Prefs\");
            }
            return sRootKey;
        }

        [CodeDescription("Return a special Url.")]
        public static string GetUrl(string sWhatUrl)
        {
            switch (sWhatUrl)
            {
                case "AutoResponderHelp":
                    return (sRootUrl + "help/AutoResponder.asp");

                case "ChangeList":
                    return (sSecureRootUrl + "fiddler2/version.asp?ver=");

                case "FiltersHelp":
                    return (sRootUrl + "help/Filters.asp");

                case "HelpContents":
                    return (sRootUrl + "help/?ver=");

                case "REDIR":
                    return "http://fiddler2.com/r/?";

                case "VerCheck":
                    return (sRootUrl + "updatecheck.asp?isBeta=");

                case "InstallLatest":
                    if (bIsBeta)
                    {
                        return (sSecureRootUrl + "r/?GetFiddler2Beta");
                    }
                    return (sSecureRootUrl + "r/?GetFiddler2");

                case "ShopAmazon":
                    return "http://fiddler2.com/r/?shop";
            }
            return sRootUrl;
        }

        internal static void PerformISAFirewallCheck()
        {
            if ((m_bCheckForISA && !bQuietMode) && !bIsViewOnly)
            {
                try
                {
                    if (File.Exists(GetPath("PerUser-ISA-Config")))
                    {
                        StreamReader reader = File.OpenText(GetPath("PerUser-ISA-Config"));
                        string str = reader.ReadToEnd();
                        reader.Close();
                        if (str.Contains("EnableWebProxyAutoConfig=1"))
                        {
                            ShowISAFirewallWarning();
                            return;
                        }
                        if (str.Contains("EnableWebProxyAutoConfig=0"))
                        {
                            return;
                        }
                    }
                    if (File.Exists(GetPath("PerMachine-ISA-Config")))
                    {
                        StreamReader reader2 = File.OpenText(GetPath("PerMachine-ISA-Config"));
                        string str2 = reader2.ReadToEnd();
                        reader2.Close();
                        if (str2.Contains("EnableWebProxyAutoConfig=1"))
                        {
                            ShowISAFirewallWarning();
                        }
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        internal static void PerformProxySettingsPerUserCheck()
        {
            if (!bIsViewOnly && !bQuietMode)
            {
                try
                {
                    RegistryKey oReg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings", false);
                    if (oReg != null)
                    {
                        if (Utilities.GetRegistryInt(oReg, "ProxySettingsPerUser", 1) == 0)
                        {
                            bool flag = Utilities.IsUserAnAdmin();
                            FiddlerApplication.Log.LogFormat("!WARNING Fiddler has detected that system or domain Group Policy has set ProxySettingsPerUser to 0. Unless Fiddler is run Elevated (e.g. Run As Administrator), it may not capture traffic from Internet Explorer and other programs. Current process {0} running Elevated.", new object[] { flag ? "IS" : "IS NOT" });
                            if (!flag && FiddlerApplication.Prefs.GetBoolPref("fiddler.proxy.WarnIfElevationRequired", true))
                            {
                                switch (MessageBox.Show("Fiddler has detected that system policy requires per-Machine proxy settings. Fiddler may not be able to watch traffic from Internet Explorer and other programs unless run as Adminstrator.\n\nWould you like to learn more?\n\nTo disable this warning, click 'Cancel'.", "Possible Conflict Detected", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk))
                                {
                                    case DialogResult.Yes:
                                        Utilities.LaunchHyperlink(GetUrl("REDIR") + "PerMachineProxy");
                                        break;

                                    case DialogResult.Cancel:
                                        FiddlerApplication.Prefs.SetBoolPref("fiddler.proxy.WarnIfElevationRequired", false);
                                        break;
                                }
                            }
                        }
                        oReg.Close();
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        internal static void RetrieveFormSettings(frmViewer f)
        {
            if (!bRevertToDefaultLayout)
            {
                try
                {
                    RegistryKey oReg = Registry.CurrentUser.OpenSubKey(GetRegPath("UI"), RegistryKeyPermissionCheck.ReadSubTree);
                    if (oReg != null)
                    {
                        bAutoScroll = Utilities.GetRegistryBool(oReg, "AutoScroll", bSmartScroll);
                        bSearchUnmarkOldHits = Utilities.GetRegistryBool(oReg, "SearchUnmarkOldHits", bSearchUnmarkOldHits);
                        bSmartScroll = Utilities.GetRegistryBool(oReg, "SmartScroll", bSmartScroll);
                        bResetCounterOnClear = Utilities.GetRegistryBool(oReg, "ResetCounterOnClear", bResetCounterOnClear);
                        f.miSessionListScroll.Checked = bAutoScroll;
                        f.miViewAutoScroll.Checked = bAutoScroll;
                        f.Bounds = new Rectangle(Utilities.GetRegistryInt(oReg, f.Name + "_Left", f.Left), Utilities.GetRegistryInt(oReg, f.Name + "_Top", f.Top), Utilities.GetRegistryInt(oReg, f.Name + "_Width", f.Width), Utilities.GetRegistryInt(oReg, f.Name + "_Height", f.Height));
                        f.pnlSessions.Width = (int) oReg.GetValue("pnlSessions_Width", f.pnlSessions.Width);
                        f.tabsRequest.Height = (int) oReg.GetValue("tabsRequest_Height", f.tabsRequest.Height);
                    }
                    Screen screen = Screen.FromRectangle(f.DesktopBounds);
                    Rectangle rectangle = Rectangle.Intersect(f.DesktopBounds, screen.WorkingArea);
                    if (rectangle.IsEmpty || ((rectangle.Width * rectangle.Height) < ((0.2 * f.Width) * f.Height)))
                    {
                        f.SetDesktopLocation(screen.WorkingArea.Left + 20, screen.WorkingArea.Top + 20);
                    }
                    if (oReg != null)
                    {
                        FormWindowState state = (FormWindowState) oReg.GetValue(f.Name + "_WState", f.WindowState);
                        if (state != FormWindowState.Minimized)
                        {
                            f.WindowState = state;
                        }
                        if (f.pnlSessions.Width > (f.Width - 50))
                        {
                            f.pnlSessions.Width = f.Width - 0x2d;
                        }
                        if (f.tabsRequest.Height > (f.Height - 250))
                        {
                            f.tabsRequest.Height = f.Height - 0xf5;
                        }
                        if (f.pnlSessions.Width < 0x19)
                        {
                            f.pnlSessions.Width = 0x19;
                        }
                        if (f.tabsRequest.Height < 0x19)
                        {
                            f.tabsRequest.Height = 0x19;
                        }
                        string str = (string) oReg.GetValue("lvSessions_Columns");
                        if (str != null)
                        {
                            int num = 0;
                            foreach (string str2 in str.Split(new char[] { '\x00a7' }, StringSplitOptions.RemoveEmptyEntries))
                            {
                                int num2;
                                string sColumnTitle = Utilities.TrimAfter(str2, "~");
                                if (!int.TryParse(Utilities.TrimBefore(str2, "~"), out num2))
                                {
                                    num2 = -1;
                                }
                                ColumnHeader header = f.lvSessions.FindColumnByTitle(sColumnTitle);
                                if (header != null)
                                {
                                    if (num2 != -1)
                                    {
                                        header.Width = num2;
                                    }
                                    header.DisplayIndex = num++;
                                }
                            }
                        }
                        oReg.Close();
                    }
                    int iLayoutMode = FiddlerApplication.Prefs.GetInt32Pref("fiddler.ui.layout.mode", 0);
                    if (iLayoutMode > 0)
                    {
                        f.actChangeToLayout(iLayoutMode);
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        internal static void SaveSettings(frmViewer f)
        {
            if (!bIsViewOnly)
            {
                RegistryKey oReg = Registry.CurrentUser.CreateSubKey(GetRegPath("UI"), RegistryKeyPermissionCheck.ReadWriteSubTree);
                oReg.SetValue("AutoScroll", bAutoScroll);
                oReg.SetValue("SmartScroll", bSmartScroll);
                oReg.SetValue("SearchUnmarkOldHits", bSearchUnmarkOldHits);
                oReg.SetValue("ResetCounterOnClear", bResetCounterOnClear);
                oReg.SetValue(f.Name + "_WState", (int) f.WindowState);
                if (f.WindowState != FormWindowState.Normal)
                {
                    if (!f.Visible)
                    {
                        f.Visible = true;
                    }
                    f.WindowState = FormWindowState.Normal;
                }
                oReg.SetValue(f.Name + "_Top", f.Top);
                oReg.SetValue(f.Name + "_Left", f.Left);
                oReg.SetValue(f.Name + "_Height", f.Height);
                oReg.SetValue(f.Name + "_Width", f.Width);
                if (!f.miViewStacked.Checked)
                {
                    oReg.SetValue("pnlSessions_Width", f.pnlSessions.Width);
                }
                oReg.SetValue("tabsRequest_Height", f.tabsRequest.Height);
                string[] strArray = new string[f.lvSessions.Columns.Count];
                for (int i = 0; i < f.lvSessions.Columns.Count; i++)
                {
                    strArray[f.lvSessions.Columns[i].DisplayIndex] = string.Format("{0}~{1}", f.lvSessions.Columns[i].Text, f.lvSessions.Columns[i].Width.ToString());
                }
                oReg.SetValue("lvSessions_Columns", string.Join("\x00a7", strArray));
                oReg.Close();
                oReg = Registry.CurrentUser.CreateSubKey(sRootKey);
                oReg.SetValue("StartupCount", iStartupCount);
                Utilities.SetRegistryString(oReg, "FontSize", flFontSize.ToString(CultureInfo.InvariantCulture));
                if (colorDisabledEdit != (SystemInformation.HighContrast ? COLOR_HICONTRASTDARK_DISABLEDEDIT : COLOR_DEFAULT_DISABLEDEDIT))
                {
                    oReg.SetValue("colorDisabledEdit", colorDisabledEdit.ToArgb());
                }
                else
                {
                    oReg.DeleteValue("colorDisabledEdit", false);
                }
                oReg.SetValue("AttachOnBoot", bAttachOnBoot);
                oReg.SetValue("AllowRemote", m_bAllowRemoteConnections);
                oReg.SetValue("ReuseServerSockets", bReuseServerSockets);
                oReg.SetValue("ReuseClientSockets", bReuseClientSockets);
                Utilities.SetRegistryString(oReg, "FiddlerBypass", sHostsThatBypassFiddler);
                oReg.SetValue("ReportHTTPErrors", bReportHTTPErrors);
                oReg.SetValue("UseGateway", bForwardToGateway);
                oReg.SetValue("CaptureCONNECT", bCaptureCONNECT);
                oReg.SetValue("CaptureFTP", bCaptureFTP);
                oReg.SetValue("EnableIPv6", bEnableIPv6);
                oReg.SetValue("BreakOnImages", bBreakOnImages);
                oReg.SetValue("MapSocketToProcess", bMapSocketToProcess);
                oReg.SetValue("UseLegacyEncryptionForSaz", !bUseAESForSAZ);
                oReg.SetValue("AutoStreamAudioVideo", bStreamAudioVideo);
                oReg.SetValue("CaptureHTTPS", bMITM_HTTPS);
                oReg.SetValue("IgnoreServerCertErrors", bIgnoreServerCertErrors);
                oReg.SetValue("CheckForUpdates", bVersionCheck);
                oReg.SetValue("HookAllConnections", bHookAllConnections);
                oReg.SetValue("HookWithPAC", bHookWithPAC);
                oReg.SetValue("ShowProcessFilter", (int) iShowProcessFilter);
                oReg.SetValue("HTTPSProcessFilter", (int) DecryptWhichProcesses);
                oReg.SetValue("AutoReloadScript", bAutoLoadScript);
                oReg.SetValue("HideOnMinimize", bHideOnMinimize);
                oReg.SetValue("AlwaysShowTrayIcon", bAlwaysShowTrayIcon);
                if (!bUsingPortOverride)
                {
                    oReg.SetValue("ListenPort", m_ListenPort);
                }
                oReg.SetValue("HotkeyMod", iHotkeyMod);
                oReg.SetValue("Hotkey", iHotkey);
                oReg.SetValue("CheckForISA", m_bCheckForISA);
                Utilities.SetRegistryString(oReg, "ScriptReferences", m_sAdditionalScriptReferences);
                Utilities.SetRegistryString(oReg, "JSEditor", m_JSEditor);
            }
        }

        internal static void SetNoDecryptList(string sNewList)
        {
            if (string.IsNullOrEmpty(sNewList))
            {
                oHLSkipDecryption = null;
            }
            else
            {
                oHLSkipDecryption = new HostList();
                oHLSkipDecryption.AssignFromString(sNewList);
            }
        }

        internal static void ShowISAFirewallWarning()
        {
            DialogResult no;
            if (bQuietMode)
            {
                no = DialogResult.No;
            }
            else
            {
                no = MessageBox.Show("Fiddler has detected that you may be running Microsoft Firewall client\nin Web Browser Automatic Configuration mode. This may cause\nFiddler to detach from Internet Explorer unexpectedly.\n\nWould you like to learn more?\n\nTo disable this warning, click 'Cancel'.", "Possible Conflict Detected", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Asterisk);
            }
            switch (no)
            {
                case DialogResult.Yes:
                    Utilities.LaunchHyperlink(GetUrl("REDIR") + "ISA");
                    return;

                case DialogResult.Cancel:
                    m_bCheckForISA = false;
                    break;
            }
        }

        [CodeDescription("Returns true if Fiddler is configured to accept remote clients.")]
        public static bool bAllowRemoteConnections
        {
            get
            {
                return m_bAllowRemoteConnections;
            }
            internal set
            {
                m_bAllowRemoteConnections = value;
            }
        }

        internal static bool bFIP
        {
            get
            {
                try
                {
                    return false;
                }
                catch (Exception)
                {
                }
                return false;
            }
            set
            {
                try
                {
                    RegistryKey key = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Eric Lawrence\Fiddler2");
                    if (key != null)
                    {
                        key.SetValue("SmartAssemblyReportUsage", value.ToString());
                        key.Close();
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        public static bool bRevertToDefaultLayout
        {
            [CompilerGenerated]
            get
            {
                return _bRevertToDefaultLayout;
            }
            [CompilerGenerated]
            internal set
            {
                _bRevertToDefaultLayout = value;
            }
        }

        public static ProcessFilterCategories DecryptWhichProcesses
        {
            get
            {
                return _pfcDecyptFilter;
            }
            set
            {
                _pfcDecyptFilter = value;
            }
        }

        public static bool ForceExclusivePort
        {
            get
            {
                return m_bForceExclusivePort;
            }
            internal set
            {
                m_bForceExclusivePort = value;
            }
        }

        public static bool IgnoreServerCertErrors
        {
            get
            {
                return bIgnoreServerCertErrors;
            }
            set
            {
                bIgnoreServerCertErrors = value;
            }
        }

        public static int iReverseProxyForPort
        {
            [CompilerGenerated]
            get
            {
                return _iReverseProxyForPort;
            }
            [CompilerGenerated]
            set
            {
                _iReverseProxyForPort = value;
            }
        }

        [CodeDescription("Return path to user's FiddlerScript editor.")]
        public static string JSEditor
        {
            get
            {
                if ((m_JSEditor == null) || (m_JSEditor.Length < 1))
                {
                    m_JSEditor = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + @"\Microsoft Office\office11\mse7.exe";
                    if (!File.Exists(m_JSEditor))
                    {
                        m_JSEditor = "notepad.exe";
                    }
                }
                return m_JSEditor;
            }
            set
            {
                m_JSEditor = value;
            }
        }

        public static int ListenPort
        {
            get
            {
                return m_ListenPort;
            }
            internal set
            {
                if ((value >= 0) && (value < 0x10000))
                {
                    m_ListenPort = value;
                    sFiddlerListenHostPort = Utilities.TrimAfter(sFiddlerListenHostPort, ':') + ":" + m_ListenPort.ToString();
                }
            }
        }

        public static bool QuietMode
        {
            get
            {
                return bQuietMode;
            }
            set
            {
                bQuietMode = value;
            }
        }

        public static string sHostsThatBypassFiddler
        {
            get
            {
                return m_sHostsThatBypassFiddler;
            }
            set
            {
                string str = value;
                if (str == null)
                {
                    str = string.Empty;
                }
                if ((str.IndexOf("<-loopback>", StringComparison.OrdinalIgnoreCase) < 0) && (str.IndexOf("<loopback>", StringComparison.OrdinalIgnoreCase) < 0))
                {
                    str = "<-loopback>;" + str;
                }
                m_sHostsThatBypassFiddler = str;
            }
        }

        public static string sScriptReferences
        {
            get
            {
                return ("mscorlib.dll;system.dll;system.windows.forms.dll;" + Assembly.GetExecutingAssembly().Location + ";" + m_sAdditionalScriptReferences);
            }
        }
    }
}

